<?php

namespace util;

class CommonUtil {
	
	//----------------------↘↘↘↘↘↘↘业务逻辑基础函数开始↙↙↙↙↙↙↙--------------------------------------
	
    //获取远程网页内容
    public static function get($url) {
        $ch = curl_init();
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT,60);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    
    //通过ip138获取IP地址
    public static function getIpAddr(){

        $url = 'http://ip.chinaz.com/';  //URL

        $ch = curl_init();
        $timeout = 10;
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $content = curl_exec($ch);
        curl_close($ch);

        $html = new \simple_html_dom();
        $html->load($content);
        $str = $html->find('.getlist',0);
        
        $pattern = '/\d+?\.\d+?\.\d+?\.\d+/i';
        preg_match($pattern, $str, $match);
        $ip = $match[0];
        $html->clear();

        return $ip;
        
    }

    //替换为https网址
    public static function replace2https($url){
        $url = trim($url);
        return str_replace("http://","https://",$url);
    }

    //本地记录异常
    public static function logException($e){

        CommonUtil::fwrite($msg = "\n----------↘↘↘↘↘↘↘异常发生于".date("Y-m-d H:i:s")."---------------------------------\n",'a');

        $i = 1;
        do {
            CommonUtil::fwrite($msg = "\n【【【【【【【【异常{$i}】】】】】】】】:\n",'a');
            CommonUtil::fwrite($msg = "code:".$e->getCode()."\n",'a');
            CommonUtil::fwrite($msg = "file:".$e->getFile()."\n",'a');
            CommonUtil::fwrite($msg = "line:".$e->getLine()."\n",'a');
            CommonUtil::fwrite($msg = "msg:>>>>>>>>>\n".$e->getMessage()."\n",'a');
            $i++;
        } while($e = $e->getPrevious());

        CommonUtil::fwrite($msg = "\n---------------------------------------------------\n",'a');
    }

    //数据上传到服务器得方法
    public static function curl($url, $post_data=null) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 检查证书中是否设置域名*/
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        if (!empty($post_data)) curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

        $output = curl_exec($ch);
        curl_close($ch);
        return $output;

    }
    
    //是否到了“清除IP记录”的时间
    public static function isTime2clearIp($config){
        
        if(empty($config["ip_record_time"]) || $config["ip_record_time"] == 0){
            return false;
        }
        
        //暂定到每2个月清除一次
        $formerTime = $config["ip_record_time"] + (2*30*24*60*60);
        if(time() >= $formerTime){
            return true;
        }
        
        return false;
        
    }

    //强制关闭CHROME
    //用于selenium抛出异常后，强制关闭浏览器
    public static function shutdownChrome($driver){

        if (!empty($driver)){
            try {
                $driver->quit();   //正常关闭浏览器
            }catch (\Exception $e){
            }
        }
        CommonUtil::shutdownChromeBackend();    //正常关闭后，再使用一次进程关闭，清除干净

        //清除浏览器缓存
        $dir = 'C:\Users\69446\AppData\Local\Temp';
        if(is_dir($dir)){
            CommonUtil::deleteAll($dir);
        }else{
            CommonUtil::echoStr("\n缓存目录不存在，清除任务被忽略。\n");
        }


    }

    //使用进程方式关闭
    public static function shutdownChromeBackend(){
        if(PATH_SEPARATOR==':'){
            shell.exec('/bin/ps -ef | grep "Chrome" | grep -v "grep" | awk \'{print $2}\' | xargs kill -9');
            shell.exec('/bin/ps -ef | grep "/Users/wangkun/test/chromedriver" | grep -v "grep" | awk \'{print $2}\' | xargs kill -9');

            //shell.exec("killall -9 chrome");
            //shell.exec("killall -9 chromedriver");
        }else{
            shell.exec('taskkill -f /FI "IMAGENAME eq chrome.exe"');
            shell.exec('taskkill -f /FI "IMAGENAME eq chromedriver.exe"');
        }

    }
    
    //是否检测本地IP库
    public static function isCheckLocalIp($firstStarted){
        
        if($firstStarted){  //首次启动，必定要检测“本地IP库”
            return true;
        }
        
        $num = rand(0,100); //100以内的随机数
        if($num % 50 == 0){ //   1/50的概率进行随机
            return true;
        }
        return false;
        
    }
    
    //更换IP地址
    public static function switchIP(){
        
        if (Runtime::$DEBUG) return '';
        
        system('cmd /c close_adsl.bat');    //关闭“远程ADSL”连接
        system('cmd /c adsl.bat');  //启动“远程ADSL”连接
    
    }

    //获取随机的PC 端user-agent
    public static function getPcUserAgent(){

        $userAgents = [
            'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)',    //360极速浏览器 CHROME
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36', //CHROME
            'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',   //IE 6
            'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)',   //IE 7
            'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)',   //IE 8
            'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)',   //IE 9
            'Mozilla/5.0 (compatible; WOW64; MSIE 10.0; Windows NT 6.2)',  //IE 10
            'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SE 2.X MetaSr 1.0; SE 2.X MetaSr 1.0; .NET CLR 2.0.50727; SE 2.X MetaSr 1.0)',  //搜狗浏览器
            'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0', //Firefox
            'Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11',    //Opera
            'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',   //Safari
            'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)',   //遨游浏览器
            'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; The World)',   //世界之窗
        ];

        $key = array_rand($userAgents,1);
        return $userAgents[$key];

    }

    //普通分页里，点击下一页，点击后，就直接快速获取下一页的pagesource，容易报错
    //AJAX获取页面源码，当页数比较大的时候，就会卡顿很久，就会报异常
    public static function getPageSource($driver){
        CommonUtil::echoStr("\nSleep 1秒....\n");
        sleep(1);   //等待间隔时间为1秒
        $content = '';
        try {
            $content = $driver->getPageSource();
        } catch (\Exception $e) {

        }
        if(empty($content)){
            return self::getPageSource($driver);
        }
        return $content;

    }
    
    //获得配置文件
    public static function getConfig(){
        $mysql = MysqlConnect::getIntance();
        $sql = "SELECT * FROM config";
        $config = $mysql->queryObject($sql);
        if(empty($config)){
            CommonUtil::echoStr("\n配置数据不存在，操作终止！\n");
            $mysql->close();
            exit();
        }
        return $config;
    }
    
    //转码为gb2312，主要是供CMD.exe使用的
    public static function echoStr($str){
        echo iconv("UTF-8","GBK//IGNORE",$str);
    }
    
	//----------------------↗↗↗↗↗↗↗业务逻辑基础函数结束↖↖↖↖↖↖↖--------------------------------------
	
	
	
	
	/**
	 * ----------------------↘↘↘↘↘↘↘基础函数开始↙↙↙↙↙↙↙--------------------------------------
	 */
	
    /**
     * 过滤输入内容中的html，转换成相应的字符
     */
    public static function filterHtml($str){
        $str=trim($str);
        if (strlen($str) <=0){
            return $str;
        }
        $search= array ("'<script[^>]*?>.*?</script>'si",  // 去掉 javascript
            "'<[\/\!]*?[^<>]*?>'si",          // 去掉 HTML 标记
            "'([\r\n])[\s]+'",                // 去掉空白字符
            "'&(quot|#34);'i",                // 替换 HTML 实体
            "'&(amp|#38);'i",
            "'&(lt|#60);'i",
            "'&(gt|#62);'i",
            "'&(nbsp|#160);'i"
        );                    // 作为 PHP 代码运行
    
        $replace= array ("",
            "",
            "\\1",
            "\"",
            "&",
            "<",
            ">",
            " "
        );
    
        return @preg_replace($search,$replace,$str);
    }
    
    /**
     * 生成UUID
     * @param $prefix 在UUID上加入一个扩展前缀
     */
    static function uuid($prefix = ''){
        $chars = md5(uniqid(mt_rand(), true));
        $uuid = substr($chars,0,8) . '-';
        $uuid .= substr($chars,8,4) . '-';
        $uuid .= substr($chars,12,4) . '-';
        $uuid .= substr($chars,16,4) . '-';
        $uuid .= substr($chars,20,12);
        return $prefix . $uuid;
    }
    
    /**
     * 判断[$fulltext字符串]是否包含[$keyword字符串]，不区别大小写
     * @param $fulltext	大单位
     * @param $keyword	小单位
     * 返回 true 或 false
     */
    static public function contain($fulltext,$keyword){
        $index = strripos($fulltext,$keyword);
        if($index === false){
            return false;
        }else{
            return true;
        }
    }
    
    /**
     * 简单格式时间，（年-月-日）如2014-12-14
     */
    static function formatSimpleDate($time,$format="Y-m-d"){
        return date($format,$time);
    }
    
    /**
     * 时间格式化
     */
    static function formatDate($time){
        if(empty($time) || $time == 0){
            return "";
        }
        $rtime = date ( "m-d H:i", $time );
        $htime = date ( "H:i", $time );
    
        $time = time () - $time;
    
        if ($time < 60) {
            $str = '刚刚';
        } elseif ($time < 60 * 60) {
            $min = floor ( $time / 60 );
            $str = $min . '分钟前';
        } elseif ($time < 60 * 60 * 24) {
            $h = floor ( $time / (60 * 60) );
            $str = $h . '小时前 ' . $htime;
        } elseif ($time < 60 * 60 * 24 * 3) {
            $d = floor ( $time / (60 * 60 * 24) );
            if ($d == 1){
                $str = '昨天 ' . $rtime;
            }
            else{
                $str = '前天 ' . $rtime;
            }
        } else {
            $str = $rtime;
        }
        return $str;
    }
	
    //记录日志
    static function fwrite($msg, $type = "w") {
        
        $fname = date('Y-m-d');
        $path = "logs".DIRECTORY_SEPARATOR.$fname.".txt";
        @$fp = fopen ( $path, $type );
        fwrite ( $fp, $msg . PHP_EOL );
        fclose ( $fp );
    }
    
    //IP重复日志记录
    static function ipLog($msg, $type = "w") {
    
        $fname = 'ip-'.date('Y-m-d');
        $path = "logs".DIRECTORY_SEPARATOR.$fname.".txt";
        @$fp = fopen ( $path, $type );
        fwrite ( $fp, $msg . PHP_EOL );
        fclose ( $fp );
    }
    
    //删除目录下的文件
    public static function deleteAll($directory,$subdir=false){
        if (is_dir($directory) == false){
            exit("The Directory Is Not Exist!");
        }
        $handle = opendir($directory);
        while (($file = readdir($handle)) !== false){
            if ($file != "." && $file != ".."){
                is_dir("$directory/$file")?
                self::deleteAll("$directory/$file",true):
                unlink("$directory/$file");
            }
        }
        if (readdir($handle) == false){
            closedir($handle);
            if($subdir == true){
                rmdir($directory);
            }
        }
    }

    /**
     * @param $reply
     * @return mixed大众点评处理商家回复的函数
     */
    public static function checkReply($reply){
        $replyList = explode('span>',$reply);
        return $replyList[count($replyList)-1];
    }


    /**
     * @param $time
     * @return false|string处理大众点评的回复时间的函数
     */
    public static function checkTime($time){
        $timeList = explode('-',$time);
        $date = date('Y-m-d',time());
        $dateList = explode('-',$date);
        if(intval($timeList[0]) < intval($dateList[1]) || (intval($timeList[0]) == intval($dateList[1]) && intval($timeList[1]) <= intval($dateList[2])) ){
            return date('Y-m-d H:i:s',strtotime($dateList[0].'-'.$time));
        }else{
            return date('Y-m-d H:i:s',strtotime((intval($dateList[0])-1).'-'.$time));
        }
    }



    /**
	 * ----------------------↗↗↗↗↗↗↗基础函数结束↖↖↖↖↖↖↖--------------------------------------
	 */
	
}